#!/usr/bin/perl -w
#      Author: Chifeng<chifeng@gmail.com>
#    Filename: sendmail.cgi 
#     Version: v0.1
# Description: this program for batch send email
#

use vars qw($DIR);
BEGIN {
    if ($ENV{SCRIPT_FILENAME} =~ m!(.*/)cgi!) {
	$DIR = $1;
    }else {
	$DIR = '../';
    }
    unshift @INC, $DIR . 'libs';
}
use strict;
use CGI qw(:standard);
use CGI::Carp;
use Time::Local;
use POSIX qw(strftime);
use RFC822;

sub sendmail_html {
    print header(-charset=>'gb2312');
    print start_html("Sendmail");
    print '<h2>ExtSender</h2>';
    print start_multipart_form;
    print "Sender:",textfield('sender','',45),"<BR>\n";
    print "Subject:",textfield('subject','',45),"<BR>\n";
    print "Recipient from file:",filefield(-name=>'recipientfile',-size=>45),"<BR>\n";
    print "Attach:",filefield(-name=>'attach',-size=>45),"<BR>\n";
    print 'Body:<BR><textarea name="body" style="width:700px; height:350px;font-size:14px;font-family:Arial;padding:5px;"></textarea><BR>';
    print reset(-name=>'reset',-value=>'Cancel'),submit(-name=>'submit',-value=>'send');
    print endform;
}

sendmail_html ();

my $sender = param('sender');
my $subject = param('subject');
my $datetime = strftime("%Y-%m-%d %H:%M:%S", localtime);
my $body = param('body');
my $rf = param('recipientfile');
my $attach = param('attach');
my $boundary = sprintf "=_%s_%s_%s", int(rand(100)), $$, time if ($attach);
my $chst = 'gb2312';
my $recipient;
my $sendmail = "/usr/sbin/sendmail -oi -t -f \"$sender\"";
if ($rf && $sender && $subject) {
    my $mimetype = uploadInfo($rf)->{'Content-Type'} || '';
    print $mimetype."<br>\n"; 
    print "\n<br>\n";
    while(<$rf>){
        $recipient = $_;
	if ( $recipient !~ /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/ ){
	    print "$recipient not email address\n<BR>";
	}else{
	    open(WFH, "|$sendmail");
	    print WFH "From: $sender\n";
	    print WFH "Subject: ".rfc822_encode_str($chst,$subject)."\n";
	    print WFH "To: $recipient \n";
	    print WFH "Date: $datetime"."\n";
	    print WFH "Mime-Version: 1.0\n";
	    print WFH "X-Originating-Ip: [$ENV{REMOTE_ADDR}]\n";
	    print WFH "X-Mailer: ExtSender\n";
	    print WFH "Content-Type: text/html; charset=$chst";
	    print WFH "\n\n";
	    print WFH "$body";
	    if($attach){
		print WFH "--$boundary\n";
	    }
	    close WFH;
	    print "$recipient sent success! \n<br>";
	}
    }
    close $rf;
}else{
    print "You must input Sender,Subject and Recipient from file"; }
print end_html;
